// 业务数据分析功能实现

DOM.on(window, 'load', () => {
  // 模拟图表数据生成
  function generateChartData() {
    const orders = dataManager.data.orders;
    const products = dataManager.data.products;
    
    // 按日期统计销售额
    const salesByDate = {};
    const last30Days = [];
    
    // 生成过去30天的日期
    for (let i = 29; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const dateStr = date.toLocaleDateString('zh-CN').split('/').slice(1).join('-'); // MM-DD格式
      last30Days.push(dateStr);
      salesByDate[dateStr] = 0;
    }
    
    // 统计每天的销售额
    orders.forEach(order => {
      if (order.status === 'PAID' || order.status === 'SHIPPED' || 
          order.status === 'DELIVERED' || order.status === 'COMPLETED') {
        const orderDate = new Date(order.createdAt);
        const dateStr = `${String(orderDate.getMonth() + 1).padStart(2, '0')}-${String(orderDate.getDate()).padStart(2, '0')}`;
        if (salesByDate.hasOwnProperty(dateStr)) {
          salesByDate[dateStr] += order.totalAmount;
        }
      }
    });
    
    // 统计订单来源分布
    const orderSources = {
      '直接访问': 0,
      '搜索引擎': 0,
      '社交媒体': 0,
      '广告推广': 0,
      '其他渠道': 0
    };
    
    // 随机分配订单来源（模拟数据）
    orders.forEach(() => {
      const sources = Object.keys(orderSources);
      const randomSource = sources[Math.floor(Math.random() * sources.length)];
      orderSources[randomSource]++;
    });
    
    // 统计热销商品
    const productSales = {};
    
    orders.forEach(order => {
      if (order.status === 'PAID' || order.status === 'SHIPPED' || 
          order.status === 'DELIVERED' || order.status === 'COMPLETED') {
        order.products.forEach(product => {
          if (!productSales[product.productName]) {
            productSales[product.productName] = 0;
          }
          productSales[product.productName] += product.quantity;
        });
      }
    });
    
    // 转换为数组并排序
    const topSellingProducts = Object.entries(productSales)
      .map(([name, quantity]) => ({ name, quantity }))
      .sort((a, b) => b.quantity - a.quantity)
      .slice(0, 10);
    
    return {
      salesByDate: salesByDate,
      last30Days: last30Days,
      orderSources: orderSources,
      topSellingProducts: topSellingProducts
    };
  }
  
  // 渲染销售趋势图表（简单的条形图模拟）
  function renderSalesTrend() {
    const chartData = generateChartData();
    const salesTrendContainer = DOM.$('#analytics-view .card:first-child div[style*="height: 300px"]');
    
    if (salesTrendContainer) {
      let html = '<div style="height: 100%; padding: 20px;">';
      html += '<svg width="100%" height="100%" viewBox="0 0 800 250">';
      
      // 获取最大值用于缩放
      const maxSales = Math.max(...Object.values(chartData.salesByDate));
      const scale = maxSales > 0 ? 200 / maxSales : 1;
      
      // 绘制坐标轴
      html += '<line x1="50" y1="230" x2="750" y2="230" stroke="#e0e0e0" stroke-width="2"/>';
      html += '<line x1="50" y1="230" x2="50" y2="30" stroke="#e0e0e0" stroke-width="2"/>';
      
      // 绘制数据条
      const barWidth = (700 / chartData.last30Days.length) * 0.6;
      chartData.last30Days.forEach((date, index) => {
        const sales = chartData.salesByDate[date];
        const barHeight = sales * scale;
        const x = 50 + (index * (700 / 30)) + ((700 / 30) - barWidth) / 2;
        const y = 230 - barHeight;
        
        html += `<rect x="${x}" y="${y}" width="${barWidth}" height="${barHeight}" fill="#4a6cf7" opacity="0.8"/>`;
        
        // 每隔5天显示日期标签
        if (index % 5 === 0) {
          html += `<text x="${x + barWidth/2}" y="245" font-size="10" text-anchor="middle" fill="#666">${date}</text>`;
        }
        
        // 显示数值（只显示部分以避免拥挤）
        if (index % 3 === 0 && sales > 0) {
          html += `<text x="${x + barWidth/2}" y="${y - 5}" font-size="9" text-anchor="middle" fill="#333">¥${Math.round(sales)}</text>`;
        }
      });
      
      html += '</svg>';
      html += '</div>';
      
      salesTrendContainer.innerHTML = html;
    }
  }
  
  // 渲染订单来源饼图（简单模拟）
  function renderOrderSources() {
    const chartData = generateChartData();
    const orderSourcesContainer = DOM.$('#analytics-view .grid .card:last-child div[style*="height: 300px"]');
    
    if (orderSourcesContainer) {
      let html = '<div style="height: 100%; padding: 20px; display: flex; justify-content: space-between;">';
      
      // 绘制简单的饼图表示（用矩形块模拟）
      html += '<div style="width: 50%; display: flex; align-items: center; justify-content: center;">';
      html += '<div style="width: 200px; height: 200px; border-radius: 50%; background: conic-gradient(';
      
      const colors = ['#4a6cf7', '#2ecc71', '#f1c40f', '#e74c3c', '#95a5a6'];
      const totalOrders = Object.values(chartData.orderSources).reduce((sum, count) => sum + count, 0);
      let startAngle = 0;
      
      Object.entries(chartData.orderSources).forEach(([source, count], index) => {
        const percentage = (count / totalOrders) * 100;
        const angle = (percentage / 100) * 360;
        html += `${colors[index]} ${startAngle}deg, ${colors[index]} ${startAngle + angle}deg, `;
        startAngle += angle;
      });
      
      html = html.slice(0, -2); // 移除最后的逗号和空格
      html += ')"></div>';
      html += '</div>';
      
      // 图例
      html += '<div style="width: 45%; display: flex; flex-direction: column; justify-content: center; gap: 15px;">';
      Object.entries(chartData.orderSources).forEach(([source, count], index) => {
        const percentage = ((count / totalOrders) * 100).toFixed(1);
        html += `<div style="display: flex; align-items: center; gap: 10px;">`;
        html += `<div style="width: 20px; height: 20px; background: ${colors[index]}; border-radius: 4px;"></div>`;
        html += `<div style="font-size: 14px;">${source}: ${count} (${percentage}%)</div>`;
        html += `</div>`;
      });
      html += '</div>';
      
      html += '</div>';
      
      orderSourcesContainer.innerHTML = html;
    }
  }
  
  // 渲染热销商品排行榜
  function renderTopSellingProducts() {
    const chartData = generateChartData();
    const topProductsContainer = DOM.$('#analytics-view .card:last-child div[style*="height: 400px"]');
    
    if (topProductsContainer) {
      let html = '<div style="height: 100%; padding: 20px;">';
      html += '<svg width="100%" height="100%" viewBox="0 0 900 350">';
      
      // 获取最大值用于缩放
      const maxQuantity = Math.max(...chartData.topSellingProducts.map(p => p.quantity));
      const scale = maxQuantity > 0 ? 250 / maxQuantity : 1;
      
      // 绘制坐标轴
      html += '<line x1="200" y1="320" x2="850" y2="320" stroke="#e0e0e0" stroke-width="2"/>';
      html += '<line x1="200" y1="320" x2="200" y2="20" stroke="#e0e0e0" stroke-width="2"/>';
      
      // 绘制横向条形图
      chartData.topSellingProducts.forEach((product, index) => {
        const barWidth = product.quantity * scale;
        const y = 50 + (index * 30);
        
        // 条形
        html += `<rect x="200" y="${y}" width="${barWidth}" height="20" fill="#2ecc71" opacity="0.8"/>`;
        
        // 商品名称
        html += `<text x="190" y="${y + 15}" font-size="12" text-anchor="end" fill="#333" font-weight="500">${product.name.length > 20 ? product.name.substring(0, 20) + '...' : product.name}</text>`;
        
        // 销量
        html += `<text x="${200 + barWidth + 10}" y="${y + 15}" font-size="12" fill="#666">${product.quantity}</text>`;
      });
      
      html += '</svg>';
      html += '</div>';
      
      topProductsContainer.innerHTML = html;
    }
  }
  
  // 初始化数据分析页面
  function initAnalytics() {
    // 监听视图切换事件
    DOM.on(document, 'viewChanged', (e) => {
      if (e.detail.viewId === 'analytics') {
        setTimeout(() => {
          renderSalesTrend();
          renderOrderSources();
          renderTopSellingProducts();
        }, 100);
      }
    });
  }
  
  // 初始化
  initAnalytics();
});